<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 10/7/14
 * Time: 9:22 AM
 */

namespace Backend\Modules\Video\Controllers;

use Common\library\Common;
use Library\Constant\Constant;
use Phalcon\Paginator\Adapter\QueryBuilder as Paginator;
use Phalcon\Mvc\Model\Resultset;
use Library\Pagination\Pager as Pager;
use Backend\Modules\Video\Models\Video;
use Backend\Modules\Video\Models\VideoGroup;
use Backend\Modules\Video\Models\VideoFile;
use Backend\Modules\Video\Models\Artist;
use Backend\Modules\Video\Forms\FormSeachVideo;
use Backend\Modules\Video\Forms\FormSearchArtist;
use Backend\Modules\Video\Forms\FormSearchVideoFile;
use Backend\Modules\Video\Forms\FormSearchVideoGroup;

class AjaxVideoController extends \BackendController
{
    public function loadArtistAction($videoId)
    {
        $this->view->setTemplateAfter('empty');

        $currentPage = abs($this->request->getQuery('page', 'int', 1));
        $artistType = $this->request->get('type') ? $this->request->get('type') : Artist::ACTOR;

        $artists = Artist::find(array(
            "artist_type = $artistType"
        ));

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'data'  => $artists,
                'limit' => 20,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => 'http://localhost/javhd/javhd-admin/video/artist?page={%page_number}',
            )
        );
        $this->view->pager = $pager;
        $this->view->artistType = $artistType;
        $this->view->videoId = $videoId;
        $this->view->formSearchArtist = new FormSearchArtist();
        if($artistType == Artist::DIRECTOR)
        {
            $this->view->render("ajax-video", "modal/modal_director");
            return ;
        }
        $this->view->render("ajax-video", "modal/modal_actor");
    }

    public function seachArtistAction()
    {
        $json['success'] = false;

        if($this->request->isAjax())
        {
            $this->view->setTemplateAfter('empty');

            $currentPage = abs($this->request->getQuery('page', 'int', 1));
            //$videos = Video::find();

            $sqlWhere = '1 = 1';
            $conditionsWhere = array();

            if($this->request->hasPost('id') && $this->request->getPost('id'))
            {
                $sqlWhere .= ' AND artist.id = :id:';
                $conditionsWhere['id'] = $this->request->getPost('id');
            }

            if($this->request->hasPost('artist_type') && $this->request->getPost('artist_type'))
            {
                $sqlWhere .= ' AND artist.artist_type = :artist_type:';
                $conditionsWhere['artist_type'] = $this->request->getPost('artist_type');
            }

            if($this->request->hasPost('name') && $this->request->getPost('name'))
            {
                $sqlWhere .= ' AND artist.name LIKE :name:';
                $conditionsWhere['name'] = '%' . $this->request->getPost('name') . '%';
            }

            if($this->request->hasPost('national_id') && $this->request->getPost('national_id'))
            {
                $sqlWhere .= ' AND artist.national_id = :national_id:';
                $conditionsWhere['national_id'] = $this->request->getPost('national_id');
            }

            if($this->request->hasPost('gender') && $this->request->getPost('gender'))
            {
                $sqlWhere .= ' AND artist.gender = :gender:';
                $conditionsWhere['gender'] = $this->request->getPost('gender');
            }            

            $videoFiles = $this->modelsManager->createBuilder()
                ->from(array('artist' => '\Backend\Modules\Video\Models\Artist'))
                ->groupBy("artist.id")
                //->join('\Backend\Modules\Video\Models\VideoDescription' , 'videoDescription.video_id = video.id' , 'videoDescription')
                //->join('\Backend\Modules\Video\Models\VideoCategoryLink' , 'videoCategoryLink.video_id = video.id' , 'videoCategoryLink')
                ->limit(Constant::ITEM_PER_PAGE_20)
                ->where($sqlWhere , $conditionsWhere)
                ->orderBy('artist.id')
                ->getQuery()
                ->execute();

            if ($currentPage == 0) {
                $currentPage = 1;
            }

            $pager = new Pager(
                new Paginator(array(
                    'data'  => $videoFiles,
                    'limit' => Constant::ITEM_PER_PAGE_20,
                    'page'  => $currentPage,
                )),
                array(
                    'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                    'rangeLength' => 5,
                    'urlMask'     => '',
                )
            );
            $this->view->pager = $pager;
            $this->view->render("ajax-video", "result_search_artist");

            $json['success'] = true;
            $json['html'] = $this->view->getContent();
            $this->response->setContent(json_encode($json));
            //Return the response
            return $this->response->send();
        }
        echo json_encode($json);
    }

    public function loadVideoGroupAction($videoId)
    {
        $this->view->setTemplateAfter('empty');

        $currentPage = abs($this->request->getQuery('page', 'int', 1));
        $videoGroups = VideoGroup::find();

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'data'  => $videoGroups,
                'limit' => Constant::ITEM_PER_PAGE_20,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => 'http://localhost/javhd/javhd-admin/video/artist?page={%page_number}',
            )
        );
        $this->view->pager = $pager;
        $this->view->videoId = $videoId;
        $this->view->formSearchVideoGroup = new FormSearchVideoGroup();
        $this->view->render("ajax-video", "modal/modal_video_group");
    }

    public function seachVideoGroupAction()
    {
        $json['success'] = false;

        if($this->request->isAjax())
        {
            $this->view->setTemplateAfter('empty');

            $currentPage = abs($this->request->getQuery('page', 'int', 1));

            //$videos = Video::find();
            $sqlWhere = '1 = 1';
            $conditionsWhere = array();

            if($this->request->hasPost('id') && $this->request->getPost('id'))
            {
                $sqlWhere .= ' AND videoGroup.id = :id:';
                $conditionsWhere['id'] = $this->request->getPost('id');
            }

            if($this->request->hasPost('name') && $this->request->getPost('name'))
            {
                $sqlWhere .= ' AND videoDescription.name LIKE :name:';
                $conditionsWhere['name'] = '%' . $this->request->getPost('name') . '%';
            }

            if($this->request->hasPost('category_id') && $this->request->getPost('category_id' , 'int') > 0)
            {
                $sqlWhere .= ' AND videoCategoryLink.category_id = :category_id:';
                $conditionsWhere['category_id'] = $this->request->getPost('category_id');
            }

            if($this->request->hasPost('national_id') && $this->request->getPost('national_id' , 'int') > 0)
            {
                $sqlWhere .= ' AND videoDescription.national_id = :national_id:';
                $conditionsWhere['national_id'] = $this->request->getPost('national_id' , 'int');
            }

            $videos = $this->modelsManager->createBuilder()
                ->from(array('videoGroup' => '\Backend\Modules\Video\Models\VideoGroup'))
                ->groupBy("videoGroup.id")
                ->join('\Backend\Modules\Video\Models\VideoDescription' , 'videoDescription.video_group_id = videoGroup.id' , 'videoDescription')
                ->join('\Backend\Modules\Video\Models\VideoCategoryLink' , 'videoCategoryLink.video_group_id = videoGroup.id' , 'videoCategoryLink')
                ->limit(Constant::ITEM_PER_PAGE_20)
                ->where($sqlWhere , $conditionsWhere)
                ->orderBy('videoGroup.id')
                ->getQuery()
                ->execute();

            if ($currentPage == 0) {
                $currentPage = 1;
            }

            $pager = new Pager(
                new Paginator(array(
                    'data'  => $videos,
                    'limit' => Constant::ITEM_PER_PAGE_20,
                    'page'  => $currentPage,
                )),
                array(
                    'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                    'rangeLength' => 5,
                    'urlMask'     => '',
                )
            );
            $this->view->pager = $pager;
            $this->view->render("ajax-video", "result_search_video_group");

            $json['success'] = true;
            $json['html'] = $this->view->getContent();
            $this->response->setContent(json_encode($json));
            //Return the response
            return $this->response->send();
        }
        echo json_encode($json);
    }

    public function loadFileVideoAction($videoId)
    {
        $this->view->setTemplateAfter('empty');

        $currentPage = abs($this->request->getQuery('page', 'int', 1));
        //$videoFiles = VideoFile::find();
        $videoFilesBuilder = $this->modelsManager->createBuilder()
                ->from(array('videoFile' => '\Backend\Modules\Video\Models\VideoFile'))
                ->groupBy("videoFile.id")
                ->orderBy('videoFile.id');

        $formSearchVideoFile = new FormSearchVideoFile();

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'builder'  => $videoFilesBuilder,
                'limit' => Constant::ITEM_PER_PAGE_20,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => '',
            )
        );
        $this->view->videoId = $videoId;
        $this->view->formSearchVideoFile = $formSearchVideoFile;
        $this->view->pager = $pager;
        $this->view->render("ajax-video", "modal/modal_video_file");
    }

    public function loadVideoAction()
    {
        $this->view->setTemplateAfter('empty');

        $currentPage = abs($this->request->getQuery('page', 'int', 1));

        $video = new Video();
        $videos = $video->queryBuilderSeachVideo(array());

        $formSearchVideo = new FormSeachVideo();

        if ($currentPage == 0) {
            $currentPage = 1;
        }
        $pager = new Pager(
            new Paginator(array(
                'builder'  => $videos,
                'limit' => Constant::ITEM_PER_PAGE_20,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => '&page={%page_number}',
            )
        );
        $this->view->objectType = $this->request->get('object_type');
        $this->view->objectId = $this->request->get('object_id');
        $this->view->pager = $pager;
        $this->view->videoGroupId = $videoGroupId;
        $this->view->formSearchVideo = $formSearchVideo;
        $this->view->render("ajax-video", "modal/modal_video");
    }

    public function searchVideoAction()
    {
        if($this->request->isAjax())
        {
            $this->view->setTemplateAfter('empty');

            $currentPage = abs($this->request->getPost('page', 'int', 1));

            $video = new Video();
            $videos = $video->queryBuilderSeachVideo($this->request->getPost());

            if ($currentPage == 0) {
                $currentPage = 1;
            }

            $pager = new Pager(
                new Paginator(array(
                    'builder'  => $videos,
                    'limit' => Constant::ITEM_PER_PAGE_20,
                    'page'  => $currentPage,
                )),
                array(
                    'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                    'rangeLength' => 10,
                    'urlMask'     => '&page={%page_number}',
                )
            );
            $this->view->pager = $pager;
            $this->view->render("ajax-video", "result_search_video");

            $json['success'] = true;
            $json['html'] = $this->view->getContent();
            $this->response->setContent(json_encode($json));
            //Return the response
            return $this->response->send();
        }
    }

    public function addVideoToObjectAction()
    {
        if(!$this->request->has('object_type'))
        {
            return ;
        }
        $objectType  = $this->request->get('object_type');
        switch($objectType)
        {
            case 'video-poster':
                if($this->request->hasPost('selectVideo'))
                {
                    $selectVideos = $this->request->getPost('selectVideo');
                    $data = array();
                    foreach($selectVideos as $videoId)
                    {
                        $checkVideoHaveVideoPoster = \Backend\Modules\Video\Models\VideoPosterLink::find(array(
                            "object_id = $videoId AND object_type = 'video'"
                        ))->count();
                        if($checkVideoHaveVideoPoster <= 0)
                        {
                            $selectVideo = Video::findFirstById($videoId);
                            if($selectVideo)
                            {
                                $videoPosterLink = new \Backend\Modules\Video\Models\VideoPosterLink();
                                $videoPosterLink->setObjectId($videoId);
                                $videoPosterLink->setObjectType('video');
                                $videoPosterLink->setPosition(0);
                                $videoPosterLink->setPage('');
                                $videoPosterLink->setStatus('A');
                                if(!$videoPosterLink->save())
                                {
                                    $this->flash->error($videoPosterLink->getMessages());
                                    die(print '123');
                                }
                            }
                        }
                    }
                }
                break;

            case 'home-category':
                if($this->request->hasPost('selectVideo'))
                {
                    $id = $this->request->get('object_id');

                    $selectVideos = $this->request->getPost('selectVideo');
                    $data = array();
                    foreach($selectVideos as $videoId)
                    {
                        $checkVideoHaveHomeVideoCategory = \Backend\Modules\Video\Models\HomeVideo::find(array(
                            "home_category_id = $id AND object_id = $videoId AND object_type = 'video'"
                        ))->count();
                        if($checkVideoHaveHomeVideoCategory <= 0)
                        {
                            $selectVideo = \Backend\Modules\Video\Models\Video::findFirstById($videoId);
                            if($selectVideo)
                            {
                                $homeVideo = new \Backend\Modules\Video\Models\HomeVideo();
                                $homeVideo->setObjectId($videoId);
                                $homeVideo->setHomeCategoryId($id);
                                $homeVideo->setObjectType('video');
                                $homeVideo->setPosition(0);
                                $homeVideo->setStatus('A');
                                $homeVideo->save();
                            }
                        }
                    }
                }
            break;

            case 'video-group':
                if($this->request->hasPost('selectVideo'))
                {
                    $objectId = $this->request->get('object_id');

                    $selectVideos = $this->request->getPost('selectVideo');
                    $data = array();
                    foreach($selectVideos as $videoId)
                    {
                        $checkVideoHaveVideoGroup = \Backend\Modules\Video\Models\VideoGroupLink::find(array(
                            "video_id = $videoId AND video_group_id = $objectId"
                        ))->count();

                        if($checkVideoHaveVideoGroup <= 0)
                        {
                            $selectVideo = Video::findFirstById($videoId);
                            if($selectVideo)
                            {
                                $videoGroupLink = new \Backend\Modules\Video\Models\VideoGroupLink();
                                $videoGroupLink->setVideoId($videoId);
                                $videoGroupLink->setVideoGroupId($objectId);
                                $videoGroupLink->setPosition(0);
                                $videoGroupLink->save();
                            }
                        }
                    }
                }
                break;
        }
        return $this->response->redirect($this->request->getHTTPReferer());

    }

    public function removeVideoFromObjectAction()
    {
        if(!$this->request->has('object_type'))
        {
            return $this->response->redirect($this->request->getHTTPReferer());
            return ;
        }
        $objectType  = $this->request->get('object_type');
        switch($objectType)
        {
            case 'video-poster':
                if($this->request->hasPost('selectedVideoRemove'))
                {
                    if($this->request->hasPost('selectedVideoRemove'))
                    {
                        $selectedVideos = $this->request->getPost('selectedVideoRemove');
                        $data = array();
                        foreach($selectedVideos as $videoId)
                        {
                            $videoPosterLink = \Backend\Modules\Video\Models\VideoPosterLink::find(array(
                                "object_id = $videoId AND object_type = 'video'"
                            ))->getFirst();
                            if($videoPosterLink)
                            {
                                $videoPosterLink->delete();
                            }
                        }
                    }
                }
                break;
        }
        return $this->response->redirect($this->request->getHTTPReferer());
    }


} 